#include "sender.hpp"

StreamPusher::StreamPusher(std::string desIp, std::string port, std::string subStr){
    this->url = "rtmp://" + desIp + ":" + port + subStr;
    this->fp = nullptr;
    this->setFp();
}
StreamPusher::~StreamPusher(){
    pclose(this->fp);
    this->fp = nullptr;
}


void StreamPusher::setFp(){
    std::string fps = "25";
    if(this->fp == nullptr){
        std::stringstream command;
        command << "ffmpeg -y -f rawvideo "
                // << "-vcodec rawvideo "
                << "-pix_fmt yuv420p "
                << "-s " << 640 << "x" << 360 << " "
                << "-re -r " << fps <<" -i - -c:v libx264 "
                << "-preset ultrafast -tune zerolatency "
                << "-g 25 -bf 0 -bufsize 2048k "
                << "-minrate 300k -maxrate 2048k "
                << "-f flv "
                << "-flvflags no_duration_filesize " << this->url;

        // command << "ffmpeg ";
	    // // infile options
	    // command << "-y "			   // overwrite output files
		// 	    << "-an "			   // force format to rawvideo
		// 	    << "-f rawvideo "	   // force format to rawvideo
		// 	    << "-vcodec rawvideo " // force video rawvideo ('copy' to copy stream)
		// 	    << "-pix_fmt yuv420p "   // set pixel format to bgr24
		// 	    << "-s "			   // set frame size (WxH or abbreviation)
		// 	    << 640
		// 	    << "x"
		// 	    << 360
		// 	    << " -r  " // set frame rate (Hz value, fraction or abbreviation)
		// 	    << fps;
	    // command << " -i - "; //

	    // // outfile options
	    // command << "-vcodec libx264 "	// Hyper fast Audio and Video encoder
		// 	    << " -pix_fmt yuv420p " // set pixel format to yuv420p
		// 	    << "-preset ultrafast " // set the libx264 encoding preset to ultrafast
		// 	    << "-f flv "			// force format to flv
        //         << "-flvflags no_duration_filesize"
		// 							//   << " -flvflags no_duration_filesize "
		// 	    << this->url;
        this->fp = popen(command.str().c_str(), "w");
    }
}
void StreamPusher::push(cv::Mat& img){
    fwrite(img.data, sizeof(char), img.total() * img.elemSize(), this->fp);
    // int fd = fileno(this->fp);
    // write(fd, img.data, img.total() * img.elemSize());
}
